package NIO;

import com.sun.security.ntlm.Server;
import io.netty.channel.ServerChannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static NIO.ByteBufferUtil.debugRead;

public class NonBlockingServer {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer=ByteBuffer.allocate(16);

        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8081));

        ssc.configureBlocking(false);//set blocking to false

        List<SocketChannel> list=new ArrayList<>();
        while (true){
            SocketChannel accept = ssc.accept();
            //System.out.println("running");    这种模式下 即使没有连接，也会不断进行循环，浪费cpu
            if (accept!=null){
                System.out.println("connecting--");
                list.add(accept);
                accept.configureBlocking(false);//set blocking to false
            }
            for (SocketChannel sc:list){
                int read = sc.read(byteBuffer); //non blocking ,it will returns 0 if nothing read
                if (read>0){
                    byteBuffer.flip();
                    debugRead(byteBuffer);
                    byteBuffer.clear();
                    System.out.println("after read:"+sc);
                }
            }
        }
    }
}
